package com.xyzwps.ewa.ext

import com.xyzwps.ewa.common.ATTRIBUTE_KEY_USER_ID
import com.xyzwps.ewa.common.ServerException
import com.xyzwps.ewa.modules.user.UserId
import io.ktor.http.*
import io.ktor.util.*

/**
 * Get user id from attributes.
 * If request is unauthenticated, an [HttpStatusCode.Unauthorized] would be thrown.
 */
fun Attributes.userId(): UserId =
    userIdOrNull() ?: throw ServerException("Unauthenticated", HttpStatusCode.Unauthorized)

/**
 * Get user id from attributes, and return null if request unauthenticated.
 */
fun Attributes.userIdOrNull(): UserId? = this.getOrNull(ATTRIBUTE_KEY_USER_ID)

/**
 * Save user id into request attributes.
 *
 * This function would be called in [com.xyzwps.ewa.modules.auth.auth] if request is authenticated.
 */
fun Attributes.userId(userId: UserId) = this.put(ATTRIBUTE_KEY_USER_ID, userId)
